import axios from "axios"
import {Toast, Notify} from "vant"

export function showLoading(){
    Toast.clear();
    Toast.loading({
        message:'加载中...',
        forbidClick:true,
        loadingType:'spinner',
    })
}

export function showFail(msg) {
    Toast.clear();
    msg=msg||"未知错误";
    Notify({ type: 'danger', message: msg, duration:1000 });
}

//拦截器
// const baseURL="http://localhost:2008"
const baseURL="http://121.196.171.41:2008" 
axios.defaults.baseURL= baseURL;

//Add a request interceptor 请求发送前
axios.interceptors.request.use(function(config){
    //成功
    showLoading()
    config.headers['token'] = localStorage.getItem('token')
    return config
},function(err){
    showFail('网络异常')
    return Promise.reject(err);
})

//Add a response interceptor 响应数据结束
axios.interceptors.response.use(function(response) {
    //成功
    Toast.clear();
    console.log(response.data);
    if(response.data.code==402||response.data.code==500){
        Notify({
            message: response.data.msg || '数据异常',
            color: '#ad0000',
            background: '#ffe1e1',
        });
    }

    if(response.data.code==3000){
        Notify({
            message: response.data.msg ,
            color: '#ad0000',
            background: '#ffe1e1',
        });
        localStorage.removeItem('token');
        localStorage.removeItem('username');
    }

    return response
},function(err){
    //失败
    showFail('服务器异常')
    return Promise.reject(err);
})


//GET 请求
export const get = function(url,params,headers){
    return new Promise(function(resolve,reject){
        axios.get(url,{
            params,
            headers
        }).then(res=>{
            resolve(res.data)
        }).catch(err=>{
            reject(err)
        })
    })
}

//post 请求
export const post =function(url,body,params,headers){
    return new Promise(function(resolve,reject){
        axios.post(url,body,{
            params,
            headers
        }).then(res=>{
            resolve(res.data)
        }).catch(err=>{
            reject(err)
        })
    })
}

export {axios,baseURL}